package com.example.by.test;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by BY on 2016/4/23.
 */
public class MyTextView extends View {
    private float frontSize = 0, aftersize = 0;
    private Context context;
    private float price;
    private String[] p;
    private int frontTextWidth, afterTextWidth;
    private int textHeight;
    private Paint paint;
    private Paint paintSmall;
    private int textColor = 0;

    public MyTextView(Context context) {
        this(context, null);
        this.context = context;
    }

    public MyTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
        price = ta.getFloat(R.styleable.MyTextView_price, 0);
        frontSize = ta.getDimensionPixelSize(R.styleable.MyTextView_front_text_size, 40);
        aftersize = ta.getDimensionPixelSize(R.styleable.MyTextView_after_text_size, 25);
        p = (price + "").split("\\.");
        ta.recycle();
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        paint = new Paint();
        paint.setTextSize(frontSize);
        paintSmall = new Paint();
        paint.setAntiAlias(true);
        paintSmall.setAntiAlias(true);
        paintSmall.setTextSize(aftersize);
        paint.setColor(textColor == 0 ? Color.RED : textColor);
        paintSmall.setColor(textColor == 0 ? Color.RED : textColor);
        frontTextWidth = (int) paint.measureText(p[0] + ".");
        afterTextWidth = (int) paintSmall.measureText(p[1]);
        textHeight = (int) (-paint.getFontMetrics().top - paint.getFontMetrics().bottom);
        setMeasuredDimension(frontTextWidth + afterTextWidth + getPaddingLeft() + getPaddingRight(), textHeight + getPaddingBottom() + getPaddingTop());
    }

    public void setPrice(float price) {
        this.price = price;
        p = (price + "").split("\\.");
        if (p[1].equals("") || p[1].equals("0")) p[1] = "00";
    }

    public void setTextColor(int color) {
        textColor = color;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(p[0] + ".", getPaddingLeft(), textHeight + getPaddingTop(), paint);
        canvas.drawText(p[1] + "", getPaddingLeft() + frontTextWidth, textHeight + getPaddingTop(), paintSmall);
    }
}
